// C bindings for Zig memory management
// SPDX-License-Identifier: MPL-2.0

#include <stddef.h>
#include <stdint.h>

// External functions that need to be implemented by the Rust side
extern void* rust_alloc_frame(size_t size, size_t alignment);
extern void rust_dealloc_frame(void* ptr, size_t size);
extern void rust_flush_tlb(void);

// C wrapper functions for Zig to call Rust functions
void* zig_alloc_frame(size_t size, size_t alignment) {
    return rust_alloc_frame(size, alignment);
}

void zig_dealloc_frame(void* ptr, size_t size) {
    rust_dealloc_frame(ptr, size);
}

void zig_flush_tlb(void) {
    rust_flush_tlb();
}

// Memory barrier functions
void memory_barrier(void) {
    __asm__ volatile("" ::: "memory");
}

void read_barrier(void) {
#ifdef __x86_64__
    __asm__ volatile("lfence" ::: "memory");
#elif defined(__aarch64__)
    __asm__ volatile("dmb ld" ::: "memory");
#else
    __asm__ volatile("" ::: "memory");
#endif
}

void write_barrier(void) {
#ifdef __x86_64__
    __asm__ volatile("sfence" ::: "memory");
#elif defined(__aarch64__)
    __asm__ volatile("dmb st" ::: "memory");
#else
    __asm__ volatile("" ::: "memory");
#endif
}